/**
 *操作方法共同类
 */
var defaultActions = {
		query: function(){
			vm.search.isSearch = true;
			$table.queryParams.pageNumber = 1;
			//$table.refresh($table.queryParams);
			vm.reload();
		},
        reset:function(){
            vm.search = {};
		},
		add: function(vm){
			vm.showList = false;
			vm.title = pageData.add;
			vm.opId = "add";
		},
		saveOrUpdate: function (url , vm, defaultForm , Object,event) {
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm[Object]),
			    beforeSend:function(XMLHttpRequest){
			    	$("#validateBtn").attr("disabled", true);
			    	parent.layer.msg( pageData.onloadTip, {icon: 16,shade: [0.3, '#000'],scrollbar: false,offset: '300px', time:100000}) ;
		        },
			    success: function(r){
			        $("#validateBtn").attr("disabled", false); 
			    	if(r.code === 0){
						alert( pageData.actionSuccess , function(index){
							 vm.showList = true;
							 vm.reload(event);
						},1);
					}else{
						alert(r.msg,null,2);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {  
					$("#validateBtn").attr("disabled", false); 
				}
			});
		},
		del: function (id, url, table ) {
			var ids = [];
			if(id==null){
				if(getSelectRows(table) == null){
					return;
				}
				ids = getSelectRows(table);
			}else{
				ids.push(id);
			}
			confirm(pageData.sureDelete, function(){
				$.ajax({
					type: "POST",
				    url: url,
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							    alert(pageData.actionSuccess, function(index){
							    table.bootstrapTable('refresh');  
							},1);
						}else{
							alert(r.msg,null,2);
						}
					}
				});
			});
		},
	audit:function(status,url,vm ){
		var ids = getSelectRows($("#table"));
		if (ids == null) {
			return;
		}
		confirm(status == 1 ? pageData.sureSubmit : status == 2 ? pageData.sureAuditPass : status == 4 ? pageData.sureInject : status == 5 ? pageData.cancelInject
				: status == 8 ? pageData.sureUsed : status == 9 ? pageData.sureStopUsed : status == 6 ? pageData.surePause 
						: pageData.sureAuditNoPass ,function() {
			$.ajax({
				type:"post",
				url: url,
				data:JSON.stringify(ids),
				success:function(r) {
					if (r.code == 0) {
						alert(pageData.actionSuccess, function(index){
							vm.reload();
						},1);
					}else {
						alert(r.msg,null,2);
					}
				}
			});
		});
	},
    terminate:function(url,vm){
        var ids = getSelectRows($("#table"));
        if (ids == null) {
            return;
        }
        confirm("确定要终止选中的记录？", function() {
            $.ajax({
                type:"post",
                url: url,
                data:JSON.stringify(ids),
                success:function(r) {
                    if (r.code == 0) {
                        alert(pageData.actionSuccess, function(index){
                            vm.reload();
                        },1);
                    }else {
                        alert(r.msg,null,2);
                    }
                }
            });
        });
    },
	copy: function(url,id){
		confirm("确定要拷贝选中的记录？", function(){
			$.ajax({
				type:"post",
				url: url,
				data:JSON.stringify(id),
				success:function(r) {
					if (r.code == 0) {
						alert(pageData.actionSuccess, function(index){
							vm.reload();
						},1);
					}else {
						alert(r.msg,null,2);
					}
				}
			});
		});
	},
	update: function (id,table,url,vm,fun) {
		if(id==null){
		     if(getSelectRow(table)==null){
		       return;
		     }
			 id = getSelectRow(table);
		}			
		vm.showList = false;
        vm.title = pageData.update;
        url = url + id;
        if(logUrl!=undefined&&logUrl!=""){//日志详情url
        	url = logUrl;
        }
        console.log(url);
        $.get(url, fun);
	},
	isTheOwenr : function(id,table,vm){  //判断此消息的创建人是否当前用户(消息模板)
		if(id==null){
		     if(getSelectRow(table)==null){
		       return;
		     }
			 id = getSelectRow(table);
		}	
		var url = "../sys/sysinfo/isTheOwenr/"+id;
		$.ajax({
			type:"post",
			url: url,
			data:[],
			success:function(r) {
				if (r.code == 0) {
					 defaultActions.update(id, $("#table"),"../sys/sysinfo/info/", vm, function(r){
				        	vm["sysInfo"] = r["sysInfo"];
			                Vue.set(vm.sysInfo,"busCompanyIdList",r.sysInfo.busCompanyIdList);
			                vm.busCompanyList = r.sysInfo.busCompanyList;

				        });
				}else {
					alert(r.msg,null,2);
				}
			}
		});
	},
	detail: function (vm , id, event,type) {
		vm.update(event, id,type);	
		vm.showList = false;
		vm.title = pageData.detail;
        container.setReadOnly();
        $('.def').css('display','none');
		//$('.input-small').prop("readonly",true);
		$('.btn').hide();
		$('.btn-warning').show();
		$('textarea').prop("readonly",true);
		$('select').prop("disabled", true);
		$('select').prop("disabled", true);
		
		$('input[type=radio]').prop("disabled",true);
		window.setTimeout(function(){
			$("div.close.fileinput-remove").css("display","none");
			$('input[type=checkbox]').prop("disabled",true);
			//$("div.col-sm-3.fileupload .input-group").css("display","none");
		},200);
	},
	assiotDetail:function(id){
		defaultActions.detail(vm,id);
		$(".panel-heading").css("display","none");
		$('.btn-warning').hide();
	},
	
	
	//日志处理
	logDetail: function(){
		vm.update(event, 0);
		vm.showList = false;
		vm.title = pageData.detail;
        container.setReadOnly();
        $('.def').css('display','none');
		//$('.input-small').prop("readonly",true);
		$('.btn').hide();
		$('.btn-warning').show();
		$('textarea').prop("readonly",true);
		$('.col-sm-2 >  select').prop("disabled", true);
		$('.col-sm-3 >  select').prop("disabled", true);
		
		$('input[type=radio]').prop("disabled",true);
		window.setTimeout(function(){
			$("div.close.fileinput-remove").css("display","none");
			$('input[type=checkbox]').prop("disabled",true);
			//$("div.col-sm-3.fileupload .input-group").css("display","none");
		},200);
	},

    /**
	 * refresh table
	 *
     * @param table
     * @param defaultForm
     * @param vm
     * @param Object
     * @param isEmpty 清空勾选框
	 * @param $table
     */
    reload: function (table, defaultForm, vm, Object, isEmpty, $_t) {
    	if(logUrl != undefined && logUrl != ""){//日志详情页
    		var  url = window.location.pathname;
    		var urls = url.split("/");
			url = urls[urls.length-2]+"/"+urls[urls.length-1]+window.location.search;
			var index = url.replace(/\./g, '_').replace(/\//g, '_').replace(/:/g, '_').replace(/\?/g, '_').replace(/,/g, '_').replace(/=/g, '_').replace(/&/g, '_');
			window.parent.$('.content_tab li').each(function() {
				if ($(this).data('index') == index) {
					window.parent.Tab.closeTab($(this));
				} 
			});
			return false;
    	}
        selectionIds = isEmpty ? [] : getSelectIds(table);
        vm.showList = true;       
        if(vm.opId == "add"){
        	$table.queryParams.pageNumber = 1;
			$table.refresh($table.queryParams);
			for(var attr in vm.search){
        		vm.search[attr] = '';
        	}
			vm.opId = "";

        }else{
        	if(vm.search.isSearch != true){
            	for(var attr in vm.search){
            		vm.search[attr] = '';
            	}
            }
        	$table.refresh();
        }
		defaultForm.data('bootstrapValidator').resetForm();
        container.ignoreReadonly();
		$('.btn').show();
        $('.fileinput-remove-button').removeAttr('style');
        $('.fileinput-upload-button').removeAttr('style');
	    $('textarea').attr("readonly",false);
	    $('select').attr("disabled",false);
		$('input[type=checkbox]').attr("disabled",false);
		$('input[type=radio]').attr("disabled",false);
		$("div.col-sm-3.fileupload .input-group").css("display","inherit");
		$("div.close.fileinput-remove").css("display","initial");
	},
	assiot: function(title, pageToLoad, fun , label){
		if (label == null) {
			label = pageData.sure;
		}
        var urlAndParams = pageToLoad.split('?');
        var value = urlAndParams[1];
        pageToLoad = urlAndParams[0];
        dialogModel = BootstrapDialog.show({
		    title: title,
            closable: true,
		    draggable: true,
            message: function(dialog) {
                var $message = $('<div></div>');
                var pageToLoad = dialog.getData('pageToLoad');
                $message.load(pageToLoad);
                return $message;
            },
            data: {
                'pageToLoad': pageToLoad,
                'value': value
            },
            buttons: [{
                label:label ,
                action: fun
            }]
        });
	},
	iframeDetail:function(title, pageToLoad, height){
        dialogModel = BootstrapDialog.show({
		    title: title,
            closable: true,
		    draggable: true,
            message: function(dialog) {
                var $message = $('<div><iframe  src="'+pageToLoad+'" style="width:100%;height: ' + (height?height+'px':'auto') + ';border-width:0 "></iframe></div>');
                return $message;
            },
            buttons: [{
            	label:'退出',
            	cssClass: 'btn-warning',
                action: function(dialogRef){
                    dialogRef.close();
                }
            }]
        });
        
	}
		
};
/**
 * 存储当前页面需要设置readonly的 dom对象
 */
~(function (jquery) {
    var _$ = jquery;
    var container0 = function () {

        var instance = this;
        this.map = new Map();
        container0 = function () {
            return instance;
        };

        this._getUrl = function () {
            var url = window.location.href;
            url = url.substring(url.lastIndexOf('/'), url.lastIndexOf('.'));
            return url;
        }
    };
    /**
	 * 设置不是只读的input为readonly
     */
    container0.prototype.setReadOnly = function () {
        var url = this._getUrl(), arr = [], time = [];
        _$('.input-small').each(function (i, v) {
            if (!_$(v).attr('readonly')) {
                _$(v).prop("readonly", true);
                arr.push(v);
            }
            if (_$(v).attr('lay-key')) {
                _$(v).prop("disabled", true);
                time.push(v)
            }
        });
        this.map.set(url + '_input', arr);
        this.map.set(url + '_time', time);
    };
    /**
	 *将map中的dom东西全部移除 readonly
     */
    container0.prototype.ignoreReadonly = function () {
        var url = this._getUrl(), inputText = this.map.get(url + '_input'), timeInput = this.map.get(url + '_time');
        if (inputText) {
            inputText.forEach(function (t) {
                _$(t).prop('readonly', false);
            })
        }
        if (timeInput) {
            timeInput.forEach(function (t) {
                _$(t).prop('disabled', false);
            })
        }
    };
    window.container = container0;
})(jQuery);
var container = new container();

Vue.mixin({
    methods: {
        query: function () {
            defaultActions.query();
        },
        reset:function () {
            defaultActions.reset();
        },
		add:function () {
            vm[vm.module] = {};
            defaultActions.add(vm);
        },
		update:function (event, id) {
			defaultActions.update(id, $("#table"),actionUrl.update, vm, function(r){
				vm[vm.module] = r[vm.module];
			});
		},
        saveOrUpdate: function (event) {
            $('#defaultForm').bootstrapValidator('validate');
            if($('#defaultForm').data('bootstrapValidator').isValid()){
            	var id = vm[vm.module][vm.moduleId];
                var url = id == null || id == ''? actionUrl.save : actionUrl.update;
                defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),vm.module,event);
            }
        },
        del: function (event, id) {
            defaultActions.del(id, actionUrl.delete, $("#table") ) ;
        },
        audit:function(status){
            defaultActions.audit(status , actionUrl.audit+"?status="+status, vm);
        },
        reload: function (event) {
            defaultActions.reload($("#table"),$("#defaultForm"),vm,vm[vm.module]);
        },
        detail: function (event, id) {
            defaultActions.detail(vm, id, event);
        }
    }
});